#include "feature_data.h"
#include <cstdio>
#include <cassert>
#include <cmath>

void feature_data::load_bin(const char *fname)
{
	FILE *f = fopen(fname, "rb");
	fread(&dim, sizeof(int), 1, f);
	char *tmp = new char[sizeof(int) + sizeof(float)*dim];
	n = 0;
	while (fread(tmp, sizeof(int) + sizeof(float)*dim, 1, f) > 0)
		++n;
	delete tmp;
	fclose(f);

	lab = new int[n];
	a = new float*[n];
	f = fopen(fname, "rb");
	fread(&dim, sizeof(int), 1, f);
	for (int k = 0; k < n; ++k) {
		a[k] = new float[dim];
		fread(&lab[k], sizeof(int), 1, f);
		fread(a[k], sizeof(float)*dim, 1, f);
	}
	fclose(f);
}


void feature_data::load_obin(const char *fname, int _dim)
{
	dim = _dim;
	FILE *f = fopen(fname, "rb");
	char *tmp = new char[sizeof(int) + sizeof(double)*dim];
	n = 0;
	while (fread(tmp, sizeof(int) + sizeof(double)*dim, 1, f) > 0)
		++n;
	delete tmp;
	fclose(f);

	lab = new int[n];
	double *buf = new double[dim];
	a = new float*[n];
	f = fopen(fname, "rb");
	for (int k = 0; k < n; ++k) {
		a[k] = new float[dim];
		fread(&lab[k], sizeof(int), 1, f);
		fread(buf, sizeof(double)*dim, 1, f);
		for (int j = 0; j < dim; ++j)
			a[k][j] = (float)buf[j];
	}
	delete buf;
	fclose(f);
}


void feature_data::load_txt(const char *fname, int dim)
{
	assert(false);
}


void feature_data::load_svm(const char *fname)
{
	assert(false);
}


void feature_data::save_bin(const char *fname)
{
	FILE *f = fopen(fname, "wb");
	fwrite(&dim, sizeof(int), 1, f);
	printf("n=%d\n",n);
	for (int k = 0; k < n; ++k) {
		fwrite(&lab[k], sizeof(int), 1, f);
		fwrite(a[k], sizeof(float)*dim, 1, f);
	}
	fclose(f);
}


void feature_data::save_obin(const char *fname)
{
	assert(false);
}


void feature_data::save_txt(const char *fname)
{
	FILE *f = fopen(fname, "w");
	for (int k = 0; k < n; ++k) {
		fprintf(f, "%d", lab[k]);
		for (int i = 0; i < dim; ++i)
			fprintf(f, " %.5lf", (double)a[k][i]);
		fprintf(f, "\n");
	}
	fclose(f);
}


void feature_data::save_svm(const char *fname)
{
	FILE *f = fopen(fname, "w");
	for (int k = 0; k < n; ++k) {
		fprintf(f, "%d", lab[k]);
		for (int i = 0; i < dim; ++i) {
			double val = a[k][i];
			if (val == 0) continue;
			if (fabs(val) > 1E-3)
				fprintf(f, " %d:%.6lf", i+1, val);
			else {
				int e = 0;
				while (fabs(val) < 1E-3)
					val *= 10, --e;
				fprintf(f, " %d:%.4lfE%d", i+1, val, e);
			}
		}
		fprintf(f, "\n");
	}
	fclose(f);
}